package com.xinliu.fastchat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.xinliu.fastchat.domain.core.R;
import com.xinliu.fastchat.domain.dto.UserLoginDto;
import com.xinliu.fastchat.domain.dto.UserRegisterDto;
import com.xinliu.fastchat.domain.po.FcUser;
import com.xinliu.fastchat.mapper.FcUserMapper;
import com.xinliu.fastchat.service.IFcUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinliu.fastchat.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 心流
 * @since 2025-10-01
 */
@Service
public class FcUserServiceImpl extends ServiceImpl<FcUserMapper, FcUser> implements IFcUserService {

    @Override
    public R register(UserRegisterDto userRegisterDto) {

        if (baseMapper.exists(new LambdaQueryWrapper<FcUser>().eq(FcUser::getUsername, userRegisterDto.getUsername()))) {
            return R.error("账号已存在");
        }

        FcUser fcUser = new FcUser();

        BeanUtils.copyProperties(userRegisterDto, fcUser);

        //随机默认用户名
        fcUser.setNick("用户" + UUID.randomUUID().toString().substring(25));

        //状态
        fcUser.setStatus(0);

        fcUser.setIsDeleted(0);

        save(fcUser);

        return R.ok("注册成功");
    }

    @Override
    public R login(UserLoginDto userLoginDto) {

        FcUser fcUser = baseMapper.selectOne(new LambdaQueryWrapper<FcUser>()
                .eq(FcUser::getUsername, userLoginDto.getUsername())
                .eq(FcUser::getPassword, userLoginDto.getPassword()));

        if (fcUser != null) {

            Map<String, Object> map = new HashMap<>();

            map.put("id", fcUser.getUserId());
            map.put("nick", fcUser.getNick());
            map.put("username", fcUser.getUsername());

            String token = JWTUtils.build(map);

            return R.ok(token);
        }

        return R.error("账号或密码错误");
    }

    @Override
    public List<FcUser> search(String userIdentify) {
        return baseMapper.selectList(new LambdaQueryWrapper<FcUser>()
                .like(FcUser::getNick,userIdentify)
                .or()
                .like(FcUser::getUsername,userIdentify));
    }
}
